package com.gitee.ice1938.module.admin.core.operator.fun;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort.Order;
import org.springframework.jdbc.core.BaseRepository;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import com.gitee.ice1938.module.admin.framwork.core.MenuItem;
import com.gitee.ice1938.module.admin.framwork.core.Operation;

@Repository
public class OperatorRepository extends BaseRepository {

	@Resource
	private JdbcTemplate jdbcTemplate;

	public Page<MenuItem> queryData(Map<String, Object> param, Pageable pageable, Order order) {
		String keyword = param.get("q_search_key") == null ? null : param.get("q_search_key").toString().trim();
		List<Object> params = new ArrayList<Object>();
		StringBuilder sql = new StringBuilder();
		sql.append("SELECT * FROM sys_operator where enable_=1");
		String sqlCount = builderCountSql(sql.toString());
		if (keyword != null && !keyword.isEmpty()) {
			sql.append(" and so.title like ? )");
			params.add("%" + keyword + "%");
		}
		if (order != null) {
			sql.append(" ORDER BY ");
			if ("type".equals(order.getProperty())) {
				sql.append("type_");
			} else {
				sql.append(underscoreName(order.getProperty()));
			}
			sql.append(" ");
			sql.append(order.getDirection());
		}
		if (pageable != null) {
			sql.append(" LIMIT ");
			sql.append(pageable.getPageNumber() * pageable.getPageSize());
			sql.append(", ");
			sql.append(pageable.getPageSize());
		}
		List<MenuItem> content = jdbcTemplate.query(sql.toString(), BeanPropertyRowMapper.newInstance(MenuItem.class));
		// return PageableExecutionUtils.getPage(content, pageable, new
		// LongSupplier() {
		//
		// public long getAsLong() {
		// return jdbcTemplate.queryForObject(sqlCount.toString(),
		// params.toArray(), Long.class);
		// }
		// });
		if (pageable != null) {
			long total = jdbcTemplate.queryForObject(sqlCount.toString(), params.toArray(), Long.class);
			return new PageImpl<MenuItem>(content, pageable, total);
		}
		return new PageImpl<MenuItem>(content);
	}

	public void batchInsert(Set<Operation> operations) {
		// 禁用系统所有
		jdbcTemplate.update("update sys_operator set enable_=? where create_flag = ?", 0, "sys");
		String checkSql = "update sys_operator set enable_=? where create_flag = ? and id=?";
		String insertSql = "INSERT INTO sys_operator (id,parent_id,title,uri,capability,type_,target,icon_class,POSITION,create_flag,enable_)VALUES (?,?,?,?,?,?,?,?,?,'sys',1)";
		for (Operation operation : operations) {
			if (operation.getId().isEmpty()) {
				continue;
			}
			// 启用定义
			long total = jdbcTemplate.update(checkSql, 1, "sys", operation.getId());
			if (total <= 0) {
				// -1:页面; 0:目录; 1:菜单 ;2:按钮;
				int type = operation.getType();
				String target = "_self";
				if (operation instanceof MenuItem) {
					MenuItem menu = (MenuItem) operation;
					target = menu.getTarget();
				}
				jdbcTemplate.update(insertSql, operation.getId(), operation.getParentId(), operation.getTitle(),
				        operation.getUri(), operation.getCapability(), type, target, operation.getIconClass(),
				        operation.getPosition());
			}
		}

	}

	public List<MenuItem> findAllMenus() {
		// 类型 0：目录 1：菜单 2：按钮
		String sql = "select * FROM sys_operator where (type_=1 or type_=0) and enable_=1";
		List<MenuItem> content = jdbcTemplate.query(sql, BeanPropertyRowMapper.newInstance(MenuItem.class));
		return content;
	}

	public int update(String id, String parentId, String iconClass, Integer position) {

		return jdbcTemplate.update("update sys_operator set icon_class=?,position=?,parent_id=? where id = ?",
		        iconClass, position, parentId, id);
	}

}
